<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    @cancel="onButtonCancelClick"
    width="600px"
  >
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { userTableColumns } from './project.data';
  import { queryPlatformUserSimple } from '/@/api/project/user';
  import { addProjectUsers } from '/@/api/project/project';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetProjectUsers',
    components: { BasicModal, BasicTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);

      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const moduleName = inject<string>('UsersModuleName');

      const dataId = ref('');

      //处理过后的table数据
      const PlatformUsersData = reactive({
        users: [],
      });

      //选择的用户id集合
      const uids = ref<number[] | string[]>([]);

      const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable({
        title: '人员列表',
        dataSource: PlatformUsersData.users,
        columns: userTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        showIndexColumn: true,
        pagination: true, //关闭分页
        rowSelection: { type: 'checkbox' },
        rowKey: 'id',
        clickToRowSelect: true,
      });

      /**
       * 根据父组件传递过来的参数获取对应的数据
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        if (uids.value.length > 0) {
          uids.value = [];
        }
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        getPlatformUsersSimple();
      });

      /**
       * 获取平台用户简要信息列表
       */
      async function getPlatformUsersSimple() {
        //更新数据前先清空原来的数据，否则页面不刷新显示最新数据
        if (PlatformUsersData.users.length > 0) {
          PlatformUsersData.users = [];
        }
        //调用后端接口获取数据
        queryPlatformUserSimple({ words: '', project: '' })
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              res.forEach((user) => {
                let result = {
                  id: user.id,
                  name: user.name,
                  phone: user.phone,
                };
                PlatformUsersData.users.push(result);
              });
              console.log('PlatformUsersData', PlatformUsersData);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        //获取设置选中的用户id集合
        uids.value = getSelectRowKeys();
        try {
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          addProjectUsers({ project: dataId.value, uids: uids.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('设置成功', 2);
              }
              closeModal();
              emit('success');
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }
        //清空选中的行
        clearSelectedRowKeys();
      }

      /**
       * 点击关闭按钮
       */
      async function onButtonCancelClick() {
        //清空选中的行
        clearSelectedRowKeys();
      }

      return {
        op,
        moduleName,
        modalTitle,
        registerModal,
        registerTable,
        onButtonOkClick,
        onButtonCancelClick,
        getPlatformUsersSimple,
      };
    },
  });
</script>
